import {
  createRouter,
  createWebHistory,
  NavigationGuardNext,
  RouteLocationNormalized,
} from "vue-router";
import Home from "../views/Home/index.vue";
import store from "../store/main";
import { Message } from "../coustom/Message";
const routerHistory = createWebHistory();
const router = createRouter({
  history: routerHistory,
  routes: [
    {
      path: "/home",
      name: "home",
      component: Home,
    },
    {
      path: "/",
      redirect: "/home",
    },
    {
      path: "/login",
      name: "login",
      component: () => import("../views/Login/index.vue"),
      meta: {
        tourist: true,
      },
    },
    {
      path: "/regist",
      name: "regist",
      component: () => import("../views/Register/index.vue"),
      meta: {
        tourist: true,
      },
    },
    {
      path: "/column/:id",
      name: "column",
      component: () => import("../views/Column/index.vue"),
    },
    {
      path: "/posts/:id",
      name: "posts",
      component: () => import("../views/Post/index.vue"),
    },
    {
      path: "/create",
      name: "create",
      meta: {
        user: true,
      },
      component: () => import("../views/Create/index.vue"),
    },
    {
      path: "/modification/:id",
      name: "modification",
      meta: {
        user: true,
      },
      component: () => import("../views/Create/index.vue"),
    },
    {
      path: "/edit",
      name: "edit",
      meta: {
        user: true,
      },
      component: () => import("../views/Personal/index.vue"),
    },
    {
      path: "/:pathMatch:(.*)",
      redirect: "/",
    },
  ],
});

const checkRoule = (
  meta: any,
  next: NavigationGuardNext,
  metaKay: string,
  from?: RouteLocationNormalized
) => {
  if (meta[metaKay]) {
    switch (metaKay) {
      case "tourist":
        Message.warn("您已登录，请尝试先退出登陆");
        next("/");
        break;
      case "user":
        Message.warn("请先登录");
        let query: string = "";
        if (from) {
          query = from.path;
        }
        next({
          path: "/login",
          query: {
            path: query,
          },
        });
        break;
    }
  } else {
    next();
  }
};

router.beforeEach((to, from, next) => {
  const { meta } = to;

  const token = localStorage.getItem("token");
  if (token) {
    if (store.getters.userNme) {
      checkRoule(meta, next, "tourist");
    } else {
      store.dispatch("getUsetData").then(
        () => {
          checkRoule(meta, next, "tourist");
        },
        () => {
          localStorage.removeItem("token");
          checkRoule(meta, next, "user", from);
        }
      );
    }
  } else {
    checkRoule(meta, next, "user", from);
  }
});

export { router };
